package com.conversationboard.fulltext.index;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.LockObtainFailedException;

import com.conversationboard.config.Configuration;
import com.conversationboard.fulltext.search.Search;
import com.conversationboard.model.Message;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;

public class IndexRemover {

	public static void removeThread(int boardId, int threadId) throws CorruptIndexException, LockObtainFailedException, IOException, SQLException, NoSuchThreadException {

		File threadIndexDirectory = new File(Configuration.getInstance().getThreadIndexPath());
		File messageIndexDirectory = new File(Configuration.getInstance().getMessageIndexPath());

		/* Delete from threads index */

		Term term = new Term("id", boardId + "-" + threadId);

		IndexReader reader = IndexReader.open(threadIndexDirectory);
		reader.deleteDocuments(term);
		reader.flush();
		reader.close();

		/* Delete from messages index */

		Thread thread = Thread.get(boardId, threadId);
		IndexReader messagesReader = IndexReader.open(messageIndexDirectory);
		
		for (Message message : thread.getMessages()) {
			Term messagesTerm = new Term("id", Identifier.generateId(boardId, threadId, message.getMessageId()));
			messagesReader.deleteDocuments(messagesTerm);
		}

		messagesReader.flush();
		messagesReader.close();

		Search.reinitialiseSearchers();
	}
}
